# 共用的工具类
from functools import wraps

from flask import current_app
from flask import g
from flask import request
from flask import session

from info.models import User
from info.utils.response_code import RET


def do_index_class(index):
    if index == 1:
        return "first"
    elif index == 2:
        return "second"
    elif index == 3:
        return "third"
    return ""


def user_login_data(f):
    @wraps(f)  # 保存函数的元信息
    def wrapper(*args, **kwargs):
        # 从请求的cookies中获取的user_id
        user_id = session.get("user_id", None)

        user = None
        if user_id:
            # 尝试查询数据
            try:
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)
        # 把查询出来的值赋值给g变量
        g.user = user
        return f(*args, **kwargs)

    return wrapper


def follow_action(user):

    # 1.取到参数
    user_id = request.json.get("user_id")
    action = request.json.get("action")

    # 2.校验参数
    if not all([user_id, action]):
        return RET.PARAMERR, '参数错误'

    if action not in ('follow', 'unfollow'):
        return RET.PARAMERR, '参数错误'

    try:
        follower_id = int(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return RET.PARAMERR, '参数错误'

    # 3.查询数据
    try:
        other = User.query.get(follower_id)
    except Exception as e:
        current_app.logger.error(e)
        return RET.DBERR, '数据库查询错误'

    if not other:
        return RET.NODATA, '未查询到数据'

    if action == "follow":
        if other not in user.followers:
            if other.id != user.id:
                user.followers.append(other)
            else:
                return RET.REQERR, '不允许关注自己'

        else:
            return RET.DATAEXIST, '当前用户已被关注'
    else:
        if other in user.followers:
            user.followers.remove(other)
        else:
            return RET.DATAEXIST, '当前用户未被关注'

    return RET.OK, '操作成功'
